<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of bpServer
 *
 * @author QuangKhoi
 */
class bpServer {
    /*
     * @param soap_server
     */

    public $server;

    public function __construct($url) {
        $this->server = new soap_server();
        $this->server->configureWSDL($url);
        $this->server->decode_utf8 = false;
        $this->server->soap_defencoding = "UTF-8";
        $this->complexType();
        $this->registerProc("getLogin", array("login" => "tns:login"), array("return" => "tns:userinfo"));
        $this->registerProc("getProd", array("data" => "xsd:string"), array("return" => "xsd:string"));
        $this->registerProc("getTrendlineData", array("filter" => "tns:filter"), array("return" => "tns:trendline"));
        $this->registerProc("getTopSocialPlatformsData", array("filter" => "tns:filter"), array("return" => "tns:topSocialPlatform"));
        $this->registerProc("getSharingMetricsData", array("filter" => "tns:filter"), array("return" => "tns:sharingMetricsData"));
        $this->registerProc("getSentimentData", array("filter" => "tns:filter"), array("return" => "tns:sentiment"));
        $this->registerProc("getGenderDistributionData", array("filter" => "tns:filter"), array("return" => "tns:genderDistribution"));
        $this->registerProc("getTopLanguagesData", array("filter" => "tns:filter"), array("return" => "tns:topLanguages"));
        $this->registerProc("getGeographicDistributionData", array("filter" => "tns:filter"), array("return" => "tns:geographicDistribution"));
        $this->registerProc("getExposureData", array("filter" => "tns:filter"), array("return" => "tns:exposure"));
        $this->registerProc("getConversationMapData", array("filter" => "tns:filter"), array("return" => "tns:conversationMap"));
        $this->registerProc("saveStream", array("stream" => "tns:stream"), array("return" => "tns:stream"));
        $this->registerProc("addTask", array("userId" => "xsd:int", "streamId" => "xsd:string", "taskType" => "xsd:int",
            "taskDescription" => "xsd:string", "assignedTo" => "xsd:int", "messageId" => "xsd:int", "post" => "xsd:string", "department" => "xsd:string"), array("return" => "tns:task"));
        $this->registerProc("markComplete", array("id" => "xsd:int", "action" => "xsd:string"), array("result" => "xsd:string"));
        $this->registerProc("undoComplete", array("id" => "xsd:int"), array("result" => "xsd:string"));
        $this->registerProc("deleteTask", array("id" => "xsd:int"), array("result" => "xsd:string"));
        $this->registerProc("addUser", array("user" => "tns:user"), array("return" => "xsd:string"));
        $this->registerProc("getUser", array(), array("return" => "tns:userList"));
        $this->registerProc("addFolder", array("folderName" => "xsd:string", "parentId" => "xsd`:int"), array("return" => "xsd:string"));
        $this->registerProc("getFolder", array(), array("return" => "tns:folder"));
        $this->registerProc("getFolderType", array(), array("return" => "tns:foldertype"));
        $this->registerProc("getFolderId", array("foldername" => "xsd:string"), array("return" => "xsd:int"));
        $this->registerProc("listUser", array(), array("return" => "tns:userList"));
        $this->registerProc("listStream", array("folderid" => "xsd:int"), array("return" => "tns:streamList"));
        $this->registerProc("addTag", array("messageId" => "xsd:int", "tagId" => "xsd:int", "streamId" => "xsd:int"), array("return" => "xsd:string"));
        $this->registerProc("removeTag", array("tagId" => "xsd:int", "messageId" => "xsd:int"), array("return" => "xsd:string"));
        $this->registerProc("getTags", array("foldername" => "xsd:string"), array("return" => "xsd:int"));
        $this->registerProc("getTag", array(), array("return" => "tns:tag"));
        $this->registerProc("createTag", array("tagName" => "xsd:string", "tagKeywords" => "xsd:string", "groupId" => "xsd:string"), array("return" => "xsd:string"));
        $this->registerProc("modifyTag", array("tagId" => "xsd:int", "tagName" => "xsd:string", "tagKeywords" => "xsd:string", "groupId" => "xsd:string"), array("return" => "xsd:string"));
        $this->registerProc("deleteUser", array("userid" => "xsd:int"), array("return" => "xsd:string"));
        $this->registerProc("deleteTag", array("tagid" => "xsd:int"), array("return" => "xsd:string"));
        $this->registerProc("getInfo", array("userid" => "xsd:int"), array("return" => "xsd:userinfo"));
        $this->registerProc("getTimeZone", array("name" => "xsd:string", "location" => "xsd:string"), array("return" => "xsd:int"));
        $this->registerProc("getNameZone", array("timezone" => "xsd:int"), array("return" => "xsd:string"));
        $this->registerProc("deleteStream", array("streamId" => "xsd:int"), array("return" => "xsd:string"));
        $this->registerProc("getStream", array("streamId" => "xsd:int"), array("return" => "tns:stream"));
        $this->registerProc("postTweet", array("messasgeId" => "xsd:string", "streamId" => "xsd:string", "message" => "xsd:string"), array("return" => "xsd:string"));
        $this->registerProc("getLogedInUser", array(), array("return" => "tns:user"));
        $this->registerProc("changePassword", array("oldPassword" => "xsd:string", "newPassword" => "xsd:string"), array("return" => "xsd:string"));
        $this->registerProc("changeName", array("name" => "xsd:string"), array("return" => "xsd:string"));
        $this->registerProc("copyStream", array("streamid" => "xsd:int", "folderid" => "xsd:int"), array("return" => "xsd:string"));
        $this->registerProc("changeSentiment", array("messageId" => "xsd:int", "threadId" => "xsd:int", "score" => "xsd:int", "dateCreated" => "xsd:string", "streamId" => "xsd:int", "type" => "xsd:int", "source" => "xsd:int"), array("return" => "xsd:string"));
        $this->registerProc("getTwitters", array(), array("return" => "tns:accountList"));
        $this->registerProc("deleteTwitter", array("twitterid" => "xsd:int"), array("return" => "xsd:string"));
        $this->registerProc("postFacebookStatus", array("messasgeId" => "xsd:string", "streamId" => "xsd:string", "message" => "xsd:string", "link" => "xsd:string"), array("return" => "xsd:string"));
        $this->registerProc("getFacebooks", array(), array("return" => "tns:accountList"));
        $this->registerProc("deleteFacebook", array("facebookid" => "xsd:int"), array("return" => "xsd:string"));
        $this->registerProc("deleteFolder", array("folderId" => "xsd:string"), array("return" => "xsd:string"));
        $this->registerProc("getGoogles", array(), array("return" => "tns:accountList"));
        $this->registerProc("deleteGoogle", array("googleid" => "xsd:int"), array("return" => "xsd:string"));
        $this->registerProc("postLinkedInStatus", array("messasgeId" => "xsd:string", "streamId" => "xsd:string", "message" => "xsd:string"), array("return" => "xsd:string"));
        $this->registerProc("getLinkedIns", array(), array("return" => "tns:accountList"));
        $this->registerProc("deleteLinkedIn", array("linkedinid" => "xsd:int"), array("return" => "xsd:string"));
        $this->registerProc("getAccounts", array(), array("return" => "tns:accountList"));
        $this->registerProc("getSpikes", array("filter" => "tns:filter"), array("return" => "tns:spikes"));
        $this->registerProc("getURL", array("url" => "xsd:string"), array("return" => "tns:sitedata"));
        $this->registerProc("addMessageAction", array("messageActionType" => "xsd:int", "messageId" => "xsd:int", "threadId" => "tns:int", "streamId" => "tns:int"), array("return" => "xsd:string"));
        $this->registerProc("markAsSpam", array("messageId" => "xsd:int", "threadId" => "xsd:int", "streamId" => "tns:int", "source" => "tns:string", "author" => "tns:string"), array("return" => "xsd:string"));
        $this->registerProc("getReplies", array("threadId" => "xsd:int", "streamId" => "xsd:string", "dateFrom" => "xsd:string", "dateTo" => "xsd:string", "index" => "xsd:int", "length" => "xsd:int"), array("return" => "xsd:string"));
        $this->registerProc("shareEmail", array("sendTo" => "xsd:string", "content" => "xsd:string", "reply" => "xsd:string", "data" => "xsd:string", "streamID" => "xsd:string"), array("return" => "xsd:string"));
        $this->registerProc("comment", array("postid" => "xsd:string", "message" => "xsd:string"), array("return" => "xsd:string"));
        $this->registerProc("markAsRead", array("streamid" => "xsd:string", "threadid" => "xsd:string", "messageid" => "xsd:string"), array("return" => "xsd:string"));
        $this->registerProc("addTagofTask", array("taskId" => "xsd:int", "tagId" => "xsd:int"), array("return" => "xsd:string"));
        $this->registerProc("removeTagofTask", array("taskId" => "xsd:int", "tagId" => "xsd:int"), array("return" => "xsd:string"));
        $this->registerProc("markForSendingLater", array("messageId" => "xsd:string", "streamId" => "xsd:string"), array("return" => "xsd:string"));
        $this->registerProc("sendSMSToQueue", array("messageId" => "xsd:int", "streamId" => "xsd:string", "post" => "xsd:string", "action" => "xsd:string"), array("return" => "xsd:string"));
        $this->registerProc("sendSMSNow", array("taskId" => "xsd:int", "phoneNumber" => "xsd:string", "text" => "xsd:string"), array("return" => "xsd:string"));
        $this->registerProc("getMailHTML", array("taskIds" => "xsd:string"), array("return" => "xsd:string"));
        $this->registerProc("sendSMS", array("phoneNumber" => "xsd:string", "message" => "xsd:string"), array("return" => "xsd:string"));
        $this->registerProc("getTagMetric", array("filter" => "tns:filter"), array("return" => "xsd:string"));
        $this->registerProc("getTopSources", array("filter" => "tns:filter"), array("return" => "xsd:string"));
        $this->registerProc("saveComparison", array("id" => "xsd:int", "name" => "xsd:string", "streamId1" => "xsd:string", "streamId2" => "xsd:string"), array("return" => "xsd:string"));
        $this->registerProc("getGroups", array(), array("return" => "xsd:string"));
        $this->registerProc("listTag", array("groupId" => "xsd:int"), array("return" => "xsd:string"));
        $this->registerProc("addTagGroup", array("groupName" => "xsd:string"), array("return" => "xsd:string"));
        $this->registerProc("modifyGroup", array("groupId" => "xsd:int", "groupName" => "xsd:string"), array("return" => "xsd:string"));
        $this->registerProc("deleteGroup", array("groupId" => "xsd:int"), array("return" => "xsd:string"));
        $this->registerProc("getSentimentByPlatforms", array("filter" => "tns:filter"), array("return" => "xsd:string"));
        $this->registerProc("getSentimentBySources", array("filter" => "tns:filter"), array("return" => "xsd:string"));
    }

    public function complexType() {
        $this->server->wsdl->addComplexType("ArrayOfString", "complexType", "array", "", "SOAP-ENC:Array", array(), array(array("ref" => "SOAP-ENC:arrayType", "wsdl:arrayType" => "xsd:string[]")), "xsd:string");
        $this->server->wsdl->addComplexType("spikes", "complexType", "array", "", "SOAP-ENC:Array", array(), array(array("ref" => "SOAP-ENC:arrayType", "wsdl:arrayType" => "tns:spike[]")), "tns:spike");

        $this->server->wsdl->addComplexType('stream', 'complexType', 'struct', 'stream', '', array('streamId' => array('name' => 'streamId', 'type' => 'xsd:int'),
            'userId' => array('name' => 'userId', 'type' => 'xsd:int'),
            'name' => array('name' => 'name', 'type' => 'xsd:string'),
            'type' => array('name' => 'type', 'type' => 'xsd:int'),
            'query' => array('name' => 'query', 'type' => 'xsd:string'),
            'language' => array('name' => 'language', 'type' => 'xsd:int'),
            'location' => array('name' => 'location', 'type' => 'xsd:int'),
            'platform' => array('name' => 'platform', 'type' => 'xsd:int'),
            'externalSources' => array('name' => 'externalSources', 'type' => 'xsd:string'),
            'folderId' => array('name' => 'folderId', 'type' => 'xsd:int')));

        $this->server->wsdl->addComplexType('accountList', 'complexType', 'struct', 'accountList', '', array(
            'screenname' => array('name' => 'screenname', 'type' => 'xsd:string'),
            'accountid' => array('name' => 'accountid', 'type' => 'xsd:string')));

        /* //ComplexType for StreamList
          $this->server->wsdl->addComplexType('streamList', 'complexType', 'array', 'all', 'SOAP-ENC:Array', array(),
          array('stream' => array('ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:stream[]')),'tns:stream');
         */
        $this->server->wsdl->addComplexType('streamList', 'complexType', 'struct', 'streamList', '', array('streamid' => array('name' => 'streamid', 'type' => 'xsd:string'),
            'streamname' => array('name' => 'streamname', 'type' => 'xsd:string'),
            'folderid' => array('name' => 'folderid', 'type' => 'xsd:string')));

        $this->server->wsdl->addComplexType('message', 'complexType', 'struct', 'message', '', array('messageId' => array('name' => 'signalId', 'type' => 'xsd:int'),
            'content' => array('name' => 'userId', 'type' => 'xsd:string')));

        $this->server->wsdl->addComplexType('signal', 'complexType', 'struct', 'signals', '', array('signalId' => array('name' => 'signalId', 'type' => 'xsd:int'),
            'userId' => array('name' => 'userId', 'type' => 'xsd:int'),
            'signalId' => array('name' => 'signalId', 'type' => 'xsd:int'),
            'streamID' => array('name' => 'signalId', 'type' => 'xsd:int'),
            'signalType' => array('name' => 'signalId', 'type' => 'xsd:int'),
            'date' => array('name' => 'signalId', 'type' => 'xsd:string'),
            'gender' => array('name' => 'signalId', 'type' => 'xsd:int'),
            'tag' => array('name' => 'signalId', 'type' => 'xsd:string'),
            'sentiment' => array('name' => 'signalId', 'type' => 'xsd:int'),
            'sharecount' => array('name' => 'signalId', 'type' => 'xsd:int'),
            'message' => array('name' => 'signalId', 'type' => 'xsd:message'),
            'image' => array('name' => 'signalId', 'type' => 'xsd:string'),
            'imageDescription' => array('name' => 'imageDescription', 'type' => 'xsd:string')));

        //ComplexType for Task
        $this->server->wsdl->addComplexType('task', 'complexType', 'struct', 'task', '', array(
            'taskId' => array('name' => 'taskId', 'type' => 'xsd:int'),
            'taskName' => array('name' => 'taskName', 'type' => 'xsd:int'),
            'taskContent' => array('name' => 'taskContent', 'type' => 'xsd:int'),
            'taskUserId' => array('name' => 'taskUserId', 'type' => 'xsd:int'),
            'taskAssignedTo' => array('name' => 'taskAssignedTo', 'type' => 'xsd:int'),
            'taskDateCreated' => array('name' => 'taskDateCreated', 'type' => 'xsd:int'),
            'taskType' => array('name' => 'taskType', 'type' => 'xsd:int'),
            'signalId' => array('name' => 'signalId', 'type' => 'xsd:int'),
            'status' => array('name' => 'status', 'type' => 'xsd:int'),
            'streamId' => array('name' => 'streamId', 'type' => 'xsd:int'),
            'messageId' => array('name' => 'messageId', 'type' => 'xsd:int'),
            'post' => array('name' => 'post', 'type' => 'xsd:string')));

        //ComplexType for Filter
        $this->server->wsdl->addComplexType('filter', 'complexType', 'struct', 'filter', '', array(
            'streamId' => array('name' => 'streamId', 'type' => 'xsd:int'),
            'dateFrom' => array('name' => 'dateFrom', 'type' => 'xsd:string'),
            'dateTo' => array('name' => 'dateTo', 'type' => 'xsd:string'),
            'language' => array('name' => 'language', 'type' => 'xsd:int'),
            'location' => array('name' => 'location', 'type' => 'xsd:int'),
            'platform' => array('name' => 'platform', 'type' => 'xsd:int'),
            'tag' => array('name' => 'tag', 'type' => 'xsd:int'),
            'sentiment' => array('name' => 'sentiment', 'type' => 'xsd:int'),
            'gender' => array('name' => 'gender', 'type' => 'xsd:int'),
            'reach' => array('name' => 'reach', 'type' => 'xsd:int'),
            'type' => array('name' => 'type', 'type' => 'xsd:int')));

        //ComplexType for Trendline
        $this->server->wsdl->addComplexType('trendline', 'complexType', 'struct', 'trendline', '', array('total' => array('name' => 'total', 'type' => 'xsd:int'),
            'date' => array('name' => 'date', 'type' => 'xsd:string'),
            'data' => array('name' => 'data', 'type' => 'xsd:string')));

        //ComplexType for Sentiment
        $this->server->wsdl->addComplexType('sentiment', 'complexType', 'struct', 'sentiment', '', array('overal' => array('name' => 'overal', 'type' => 'xsd:string'),
            'date' => array('name' => 'date', 'type' => 'xsd:string'),
            'data' => array('name' => 'data', 'type' => 'xsd:string'),
            'percent' => array('name' => 'percent', 'type' => 'xsd:string')));

        //ComplexType for TopSocialPlatforms
        $this->server->wsdl->addComplexType('topSocialPlatform', 'complexType', 'struct', 'topSocialPlatform', '', array('name' => array('name' => 'name', 'type' => 'xsd:string'),
            'data' => array('name' => 'data', 'type' => 'xsd:string'),
            'trend' => array('name' => 'trend', 'type' => 'xsd:string')));

        //ComplexType for SharingMetrics
        $this->server->wsdl->addComplexType('sharingMetricsData', 'complexType', 'struct', 'topSocialPlatform', '', array('name' => array('name' => 'name', 'type' => 'xsd:string'),
            'data' => array('name' => 'data', 'type' => 'xsd:string')));

        //ComplexType for Login
        $this->server->wsdl->addComplexType('login', 'complexType', 'struct', 'login', '', array(
            'email' => array('name' => 'email', 'type' => 'xsd:string'),
            'password' => array('name' => 'password', 'type' => 'xsd:string')));

        //ComplexType for UserInfo
        $this->server->wsdl->addComplexType('userinfo', 'complexType', 'struct', 'userinfo', '', array(
            'email' => array('name' => 'email', 'type' => 'xsd:string'),
            'password' => array('name' => 'password', 'type' => 'xsd:string'),
            'name' => array('name' => 'name', 'type' => 'xsd:string'),
            'company' => array('name' => 'company', 'type' => 'xsd:string'),
            'address' => array('name' => 'address', 'type' => 'xsd:string'),
            'phone' => array('name' => 'phone', 'type' => 'xsd:string'),
            'position' => array('name' => 'position', 'type' => 'xsd:string'),
            'dateregistered' => array('name' => 'dateregistered', 'type' => 'xsd:date'),
            'token' => array('name' => 'token', 'type' => 'xsd:string'),
            'timezone' => array('name' => 'timezone', 'type' => 'xsd:int')));

        //ComplexType for User
        $this->server->wsdl->addComplexType('user', 'complexType', 'struct', 'user', '', array(
            'userid' => array('name' => 'userid', 'type' => 'xsd:int'),
            'email' => array('name' => 'email', 'type' => 'xsd:string'),
            'password' => array('name' => 'password', 'type' => 'xsd:string'),
            'name' => array('name' => 'name', 'type' => 'xsd:string'),
            'company' => array('name' => 'company', 'type' => 'xsd:string'),
            'address' => array('name' => 'address', 'type' => 'xsd:string'),
            'phone' => array('name' => 'phone', 'type' => 'xsd:string'),
            'position' => array('name' => 'position', 'type' => 'xsd:string'),
            'dateregistered' => array('name' => 'dateregistered', 'type' => 'xsd:date'),
            'token' => array('name' => 'token', 'type' => 'xsd:string'),
            'timezone' => array('name' => 'timezone', 'type' => 'xsd:int')));

        $this->server->wsdl->addComplexType('userList', 'complexType', 'struct', 'userList', '', array(
            'userid' => array('name' => 'userid', 'type' => 'xsd:string'),
            'username' => array('name' => 'userid', 'type' => 'xsd:string'),
            'usermail' => array('name' => 'userid', 'type' => 'xsd:string'),
            'lastlogin' => array('name' => 'userid', 'type' => 'xsd:string'),
            'avatar' => array('name' => 'userid', 'type' => 'xsd:string')));

        $this->server->wsdl->addComplexType('folder', 'complexType', 'struct', 'folder', '', array(
            'folderid' => array('name' => 'folderid', 'type' => 'xsd:string'),
            'foldername' => array('name' => 'foldername', 'type' => 'xsd:string'),
            'parentid' => array('name' => 'parentid', 'type' => 'xsd:string')));

        $this->server->wsdl->addComplexType('foldertype', 'complexType', 'struct', 'foldertype', '', array(
            'typeid' => array('name' => 'typeid', 'type' => 'xsd:int'),
            'typename' => array('name' => 'typename', 'type' => 'xsd:string')));

        $this->server->wsdl->addComplexType('tag', 'complexType', 'struct', 'tag', '', array(
            'tagid' => array('name' => 'tagid', 'type' => 'xsd:int'),
            'tagname' => array('name' => 'tagname', 'type' => 'xsd:string')));

        $this->server->wsdl->addComplexType('spike', 'complexType', 'struct', 'spikes', '', array(
            'date' => array('name' => 'date', 'type' => 'tns:ArrayOfString'),
            'trend' => array('name' => 'trend', 'type' => 'tns:ArrayOfString'),
            'value' => array('name' => 'value', 'type' => 'xsd:int'),
            'spike' => array('name' => 'spike', 'type' => 'tns:ArrayOfString')));

        $this->server->wsdl->addComplexType('spikeItems', 'complexType', 'struct', 'spikes', '', array(
            'items' => array('name' => 'items', 'type' => 'tns:ArrayOfString')));

        $this->server->wsdl->addComplexType('sitedata', 'complexType', 'struct', 'sitedata', '', array(
            'title' => array('name' => 'title', 'type' => 'tns:string'),
            'description' => array('name' => 'description', 'type' => 'tns:string')));
        
        $this->server->wsdl->addComplexType("hostInfo", 'complexType', 'struct', 'hostInfo', '', array(
            'hostname' => array('name' => 'hostname', 'type' => 'xsd:string'),
            'ip' => array('name' => 'ip', 'type' => 'xsd:string'),
            'port' => array('name' => 'port', 'type' => 'xsd:int'),
            'datetime' => array('name' => 'datetime', 'type' => 'xsd:string'),
            'PHP_version' => array('name' => 'PHP_version', 'type' => 'xsd:string'),
            ));
    }

    public function registerProc($procedure, $params, $returns, $style = "rpc", $use = "encoded", $description = "", $namespace = false, $action = false) {
        $this->server->register($procedure,
                // parameter list:
                $params,
                // return value(s):
                $returns,
                // namespace:
                $namespace,
                // soapaction: (use default)
                $action,
                // style: rpc or document
                $style,
                // use: encoded or literal
                $use,
                // description: documentation for the method
                $description);
        //self::service($http_response_header);
    }

    /*
     * SOAP Procedures
     */

    public function service($data) {
        $this->server->service($data);
    }

    public static function shareEmail($sendTo, $subject, $content) {
        return Mail::shareEmail($sendTo, $subject, $content);
    }

    public static function deleteLinkedIn($linkedinid) {
        return LinkedIn::deleteLinkedIn($linkedinid);
    }

    public static function getLinkedIns() {
        return LinkedIn::getLinkedIns();
    }

    public static function postLinkedInStatus($message) {
        return LinkedIn::postLinkedInStatus($message);
    }

    public static function getGoogles() {
        return Google::getGoogles();
    }

    public static function deleteGoogle($googleid) {
        return Google::deleteGoogle($googleid);
    }

    public static function deleteFacebook($facebookid) {
        return Facebook::deleteFacebook($facebookid);
    }

    public static function getFacebooks() {
        return Facebook::getFacebooks();
    }

    public static function postFacebookStatus($messageId, $streamId, $message, $link) {
        return Facebook::postFacebookStatus($messageId, $streamId, $message, $link);
    }

    public static function deleteTwitter($twitterid) {
        return Twitter::deleteTwitter($twitterid);
    }

    public static function getTwitters() {
        return Twitter::getTwitters();
    }

    public static function postTweet($messageId, $streamId, $message) {
        return Twitter::postTweet($messageId, $streamId, $message);
    }

    public static function copyStream($streamid, $folderid) {
        return Stream::copyStream($streamid, $folderid);
    }

    public static function getNameZone($timezone) {
        return User::getNameZone($timezone);
    }

    public static function getTimeZone($name, $location) {
        return User::getTimeZone($name, $location);
    }

    public static function getInfo() {
        return User::getInfo();
    }

    public static function createTag($tagName, $keyword, $groupId) {
        return User::createTag($tagName, $keyword, $groupId);
    }

    public static function modifyTag($tagId, $tagName, $keywords, $groupId) {
        $tag = Tag::withId($tagId);
        $tag->tagName = $tagName;
        $tag->keywords = $keywords;
        $tag->groupId = $groupId;
        if ($tag->Save())
            return "succeed";
        else
            return "failed";
    }

    public static function getTag() {
        return User::getTag();
    }

    public static function deleteTag($tagid) {
        return Tag::deleteTag($tagid);
    }

    public static function getFolderId($name) {
        return Folder::getId($name);
    }

    public static function getFolderType() {
        return FolderType::getFolderType();
    }

    public function deleteUser($userid) {
        return User::deleteUser($userid);
    }

    public static function listUser() {
        return User::listUser();
    }

    public static function listStream($folderid) {
        return Stream::listStream($folderid);
    }

    public static function getFolder() {
        return User::getFolder();
    }

    public static function addFolder($folderName, $parentId) {
        return User::addFolder($folderName, $parentId);
    }

    public static function getUser() {
        return User::getUser();
    }

    public static function addUser($user) {
        return User::addUser($user);
    }

    public static function getTrendlineData($_filter) {
        return Metrics::getTrendlineData($_filter);
    }

    public static function getTopSocialPlatformsData($_filter) {
        return Metrics::getTopSocialPlatformsData($_filter);
    }

    public function getSharingMetricsData($_filter) {
        return Metrics::getSharingMetricsData($_filter);
    }

    public function getGenderDistributionData($_filter) {
        return Metrics::getGenderDistributionData($_filter);
    }

    public function getTopLanguagesData($_filter) {
        return Metrics::getTopLanguagesData($_filter);
    }

    public function getGeographicDistributionData($_filter) {
        return Metrics::getGeographicDistributionData($_filter);
    }

    public function getExposureData($_filter) {
        return Metrics::getExposureData($_filter);
    }

    public function getConversationMapData($_filter) {
        return Metrics::getConversationMapData($_filter);
    }

    public static function addTask($userId, $taskType, $taskDescription, $assignedTo, $messageId, $streamId, $post, $department) {
        $task = Task::withData(TaskType::getName($taskType), $taskDescription, $userId, $assignedTo, new DateTime(), $taskType, '', $messageId, $post);
        $saveSignal = Signal::withData($messageId, $streamId);
        $signalController = new SignalController($saveSignal, new SignalView());
        $signalController->save();
        $task->signalId = $saveSignal->signalID;
        $task->department = $department;
        $taskController = new TaskController($task, new TaskView());
        $result = $taskController->save();
        return array(
            'taskName' => $result->taskName,
            'taskContent' => $result->taskContent,
            'taskUserId' => $result->taskUserId,
            'taskAssignedTo' => $result->taskAssignedTo,
            'taskDateCreated' => $result->taskDateCreated->format("U"),
            'taskType' => $result->taskType,
            'signalId' => $result->signalId,
            'status' => $result->status,
            'post' => $result->post
        );
    }

    public static function loadStream($streamId, $dateFrom, $dateTo, $language = 2, $location = 1, $platform = array('0'), $tags = array('0'), $sentiment = 0, $gender = 1, $reach = 0, $index = 0, $length = 10, $messageAction = '', $type = array('0'), $source = array('0')) {
        $stream = Stream::withId($streamId);
        $streamController = new StreamController($stream, new StreamView());
        $data = $streamController->render($dateFrom, $dateTo, $index, $length, $language, $tags, $sentiment, $messageAction, $type, $source);
        if ($data == 'info')
            return;
        include "View/".$GLOBALS['deviceType']."/Post/SinglePost.php";
    }

    public static function loadMetrics($streamId, $dateFrom, $dateTo, $language = 2, $location = 1, $platform = 1, $tags = "", $sentiment = 1, $gender = 1, $reach = 0) {
        $stream = Stream::withId($streamId);
        $filter = array("streamId" => $streamId, "dateFrom" => $dateFrom, "dateTo" => $dateTo, "language" => $language,
            "location" => $location, "platform" => $platform, "tag" => $tags, "sentiment" => $sentiment,
            "gender" => $gender, "reach" => $reach);
        $metricsController = new MetricsController(new Metrics(), new MetricsView());
        $metricsController->render($filter);
        include "View/".$GLOBALS['deviceType']."/Metrics/MetricsViewHTML.php";
    }

    public static function loadTopSocial($streamId, $dateFrom, $dateTo, $language = 2, $location = 1, $platform = 1, $tags = "", $sentiment = 1, $gender = 1, $reach = 0) {
        //$stream = Stream::withId($streamId);
        $filter = array("streamId" => $streamId, "dateFrom" => $dateFrom, "dateTo" => $dateTo, "language" => $language,
            "location" => $location, "platform" => $platform, "tag" => $tags, "sentiment" => $sentiment,
            "gender" => $gender, "reach" => $reach);
        $filter = array();
        $filter['streamId'] = $streamId;
        $filter['dateFrom'] = '20-09-2013';
        $filter['dateTo'] = '25-09-2013';
        $topSocialPlatformsData = Metrics::getTopSocialPlatformsData($filter);
        var_dump($topSocialPlatformsData);
        include "View/".$GLOBALS['deviceType']."/Metrics/TopSocialPlatformsHTML.php";
    }

    public static function markComplete($id, $action) {
        $task = Task::withId($id);
        $task->action = $action;
        $taskController = new TaskController($task, new TaskView());
        if ($taskController->markComplete())
            return "succeed";
        else
            return "failed";
    }

    public static function undoComplete($id) {
        $task = Task::withId($id);
        $taskController = new TaskController($task, new TaskView());
        if ($taskController->undoComplete())
            return "succeed";
        else
            return "failed";
    }

    public static function deleteTask($id) {
        $task = Task::withId($id);
        $taskController = new TaskController($task, new TaskView());
        if ($taskController->delete())
            return "succeed";
        else
            return "failed";
    }

    public static function getLogin($login) {
        return User::getLogin($login);
    }

    public static function addTag($messageId, $tagId, $streamId) {
        $query = "SELECT * FROM signals WHERE messageid = $messageId AND streamid = $streamId";
        $db = Database::getInstance();
        $result = $db->query($query);
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow == 0) {
                $saveSignal = Signal::withData($messageId, $streamId);
                $signalController = new SignalController($saveSignal, new SignalView());
                $signalController->save();
            } else {
                $signalId = $result->dataTable->rows[0]['signalid'];
                $saveSignal = Signal::withId($signalId);
            }
        } else {
            $saveSignal = Signal::withData($messageId, $streamId);
            $signalController = new SignalController($saveSignal, new SignalView());
            $signalController->save();
        }
        $tag = Tag::withId($tagId);
        return json_encode($tag->add($saveSignal->signalID));
    }

    public static function removeTag($tagId, $streamId, $messageId) {
        $user = User::getLogedInUser();
        $query = "SELECT * FROM signals WHERE streamid = '$streamId' AND messageid = $messageId AND userid IN (SELECT userid FROM users WHERE teamid = '$user->teamId')";
        $db = Database::getInstance();
        $result = $db->query($query);
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow > 0) {
                $signalId = $result->dataTable->rows[0]['signalid'];
                $saveSignal = Signal::withId($signalId);
            } else
                return 'failed';
        }
        $tag = Tag::withId($tagId);
        if ($tag->remove($saveSignal->signalID))
            return $tag->tagName;
        else
            return "failed";
    }

    public static function saveStream($streamData) {
        $stream = Stream::withData($streamData['userId'], $streamData['name'], $streamData['type'], $streamData['query'], $streamData['language'], $streamData['location'], $streamData['platform'], $streamData['externalSources'], $streamData['folderId']);
        $streamController = new StreamController($stream, new StreamView());
        $streamSources = array();
        if ($streamData['streamId']) {
            $stream->streamId = $streamData['streamId'];
            $s = Stream::withId(base64_encode($streamData['streamId']));
            $streamSources = explode(';', $s->externalSources);
        } else {
            $streamSources = explode(';', $streamData['externalSources']);
        }
        //Send email

        return (array) $streamController->save();
    }

    public static function deleteStream($streamId) {
        $stream = Stream::withId(base64_encode($streamId));
        $streamController = new StreamController($stream, new StreamView());
        if ($streamController->delete())
            return "success";
        else
            return "failed";
    }

    public static function getStream($streamid) {
        $stream = (array) Stream::withId(base64_encode($streamid));
        return $stream;
    }

    public static function getLogedInUser() {
        $user = (array) User::getLogedInUser();
        $user["userid"] = $user['id'];
        return (array) $user;
    }

    public static function changePassword($oldPassword, $newPassword) {
        return User::changePassword($oldPassword, $newPassword);
    }

    public static function changeName($name) {
        return User::changeName($name);
    }

    public static function changeSentiment($messageId, $threadId, $score, $datecreated, $streamId, $type, $source) {
        $sentiment = new Sentiment(User::getCurrentUserId(), $messageId, $threadId, $score, $datecreated, $streamId, $type, $source);
        if ($sentiment->save())
            return "succeed";
        else
            return "failed";
    }

    public static function deleteFolder($folderId) {
        $folder = Folder::withId($folderId);
        $folderController = new FolderController($folder, new FolderView());
        if ($folderController->delete())
            return "succeed";
        else
            return "failed";
    }

    public static function getAccounts() {
        return User::getAccounts();
    }

    public static function getSpikes($filter) {
        return SignalsHelper::getSpike($filter);
    }

    public static function getURL($url) {
        $html = self::file_get_contents_curl($url);

        //parsing begins here:
        $doc = new DOMDocument();
        @$doc->loadHTML($html);
        $nodes = $doc->getElementsByTagName('title');

        //get and display what you need:
        $title = $nodes->item(0)->nodeValue;

        $metas = $doc->getElementsByTagName('meta');

        for ($i = 0; $i < $metas->length; $i++) {
            $meta = $metas->item($i);
            if ($meta->getAttribute('name') == 'description')
                $description = $meta->getAttribute('content');
            if ($meta->getAttribute('name') == 'keywords')
                $keywords = $meta->getAttribute('content');
        }
        return array('title' => $title, 'description' => $description);
    }

    public static function file_get_contents_curl($url) {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

        $data = curl_exec($ch);
        curl_close($ch);

        return $data;
    }

    /**
     * Set/Remove message action
     * @param type $messageActionType
     *      1 - favorite
     *      2 - archive
     *      3 - spam
     *      4 - trash
     * @param type $messageId
     * @param type $threadId
     * @return string
     */
    public static function addMessageAction($messageActionType, $messageId, $threadId, $streamId) {
        $db = Database::getInstance();
        $id = Database::getID('messageactiondata', 'id');
        $userId = User::getCurrentUserId();
        $messageActionData = MessageAction::getByMessageId($threadId, $streamId);
        if (!$messageActionData[$messageActionType])
            $query = "INSERT INTO messageactiondata VALUES ($id, $messageId, $threadId, $userId, $messageActionType, $streamId, NOW())";
        else
            $query = "DELETE FROM messageactiondata WHERE threadid = $threadId AND userid = $userId AND type = $messageActionType AND streamid = $streamId";
        $result = $db->query($query);
        if ($result->returnCode == 200)
            return 'succeed';
        else
            return 'failed';
    }

    /**
     * Add/Remove from Spam list
     * @param type $messageId
     * @param type $threadId
     * @param type $streamId
     * @param type $source
     * @param type $author
     * @return string
     */
    public static function markAsSpam($messageId, $threadId, $streamId, $source = '', $author = '') {
        $db = Database::getInstance();
        $id = Database::getID('spammessages', 'id');
        $userId = User::getCurrentUserId();
        if ($source != '' && $author != '')
            $query = "DELETE FROM spammessages WHERE (source = '$source' OR author = '$author') AND userid = $userId AND streamid = $streamId";
        else
            $query = "INSERT INTO spammessages VALUES($id, $messageId, $threadId, $userId, '$source', '$author', $streamId)";
        $result = $db->query($query);
        if ($result->returnCode == 200)
            return 'succeed';
        else
            return 'failed';
    }

    public static function getReplies($threadId, $streamId, $dateFrom, $dateTo, $index = 0, $length = 5) {
        $stream = Stream::withId($streamId);
        $dateFrom = str_replace('/', '-', $dateFrom);
        $dateTo = str_replace('/', '-', $dateTo);
        $reader = new ZMessageReader($dateFrom, $dateTo, 7, $stream->query, $stream->language);
        $reader->filterByThread($threadId);
        global $items, $itemTotal;
        $items = array();
        $replies = array();
        $user = User::getLogedInUser();
        if ($user->type == 10) {
            $messageIds = array();
            $df = new DateTime($dateFrom);
            $dt = new DateTime($dateTo);
            $user = User::getLogedInUser();
            $dateFrom = $df->format("Y-m-d");
            $dateTo = $dt->format("Y-m-d");
            $mIds = Stream::getReplies($threadId, base64_decode($streamId), $dateFrom, $dateTo, $index, $length);
            foreach ($mIds as $id) {
                $messageIds[] = $id;
            }
            if ($messageIds > 0) {
                if (count($messageIds) == 1) {
                    $replies = array(Message::withId($messageIds));
                } else {
                    $replies = Message::withId($messageIds);
                }
                if (is_array($replies)) {
                    foreach ($replies as $item) {
                        $reply = array();
                        $reply['text'] = trim(str_replace("\n", "", Signal::removeLink($item->getText())));
                        $reply['author'] = trim($item->getAuthor());
                        $reply['likes'] = $item->getNumberOfLikes();
                        $reply['id'] = $item->getId();
                        $reply['threadId'] = $item->getThreadId();
                        $reply['time'] = $item->getTime();
                        $reply['sentiment'] = Sentiment::saveSentiment($item->getText(), base64_decode($streamId), $item->getId(), $item->getThreadId(), $item->getTime(), -1, $item->getSource());
                        $items[] = $reply;
                    }
                } else
                    return 'Your query has no result! Try again!';
            }
        } else {
            try {
                $reader->read(function($item, $total) use (&$streamId) {
                    global $items, $itemTotal;
                    $reply = array();
                    $reply['text'] = trim(str_replace("\n", "", Signal::removeLink($item->getText())));
                    $reply['author'] = trim($item->getAuthor());
                    $reply['likes'] = $item->getNumberOfLikes();
                    $reply['id'] = $item->getId();
                    $reply['threadId'] = $item->getThreadId();
                    $reply['time'] = $item->getTime();
                    $reply['sentiment'] = Sentiment::saveSentiment($item->getText(), base64_decode($streamId), $item->getId(), $item->getThreadId(), $item->getTime(), -1, $item->getSource());
                    $items[] = $reply;
                    if ($total)
                        $itemTotal = $total;
                }, $index, $length);
            } catch (Exception $e) {
                return $e->getMessage();
            }
        }
        $result = array();
        $result['items'] = $items;
        $result['total'] = $itemTotal;
        return json_encode($result);
    }

    public static function comment($fbPostID, $message) {
        return Facebook::comment($fbPostID, $message);
    }

    public static function markAsRead($streamId, $threadId, $messageId) {
        $userId = User::getCurrentUserId();
        $db = Database::getInstance();
        $query = "INSERT INTO messagestatus (userid, streamid, threadid, messageid) VALUES ($userId, '$streamId', '$threadId', '$messageId')";
        if ($db->query($query))
            return "succeed";
        else
            return "failed";
    }

    public static function isRead($streamId, $threadId, $messageId) {
        $db = Database::getInstance();
        $query = "SELECT COUNT(*) FROM messagestatus WHERE threadid = '$threadId' AND messageid = '$messageId' AND streamid = $streamId";
        //return $query.'<br>';
        $result = $db->query($query);
        return $result->dataTable->rows[0][0];
    }

    public static function addTagofTask($taskId, $tagId) {
        $task = Task::withId($taskId);
        $taskController = new TaskController($task, null);
        return $taskController->addTag($tagId);
    }

    public static function removeTagofTask($taskId, $tagId) {
        $task = Task::withId($taskId);
        $taskController = new TaskController($task, null);
        return $taskController->removeTag($tagId);
    }

    public static function markForSendingLater($messageId, $streamId, $post, $action) {
        $saveSignal = Signal::withData($messageId, $streamId);
        $signalController = new SignalController($saveSignal, new SignalView());
        $signalController->save();
        $task = Task::withData(TaskType::getName(10), "waiting for sending", User::getCurrentUserId(), User::getCurrentUserId(), new DateTime(), 10, $saveSignal->signalID, $streamId, $post);
        $task->signalId = $saveSignal->signalID;
        $task->action = $action;
        $task->post = $post;
        $result = $task;
        $taskController = new TaskController($task, new TaskView());
        if ($taskController->save())
            return "succeed";
        else
            return "failed";
    }

    public static function sendSMSToQueue($messageId, $streamId, $post, $action) {
        $saveSignal = Signal::withData($messageId, $streamId);
        $signalController = new SignalController($saveSignal, new SignalView());
        $signalController->save();
        $task = Task::withData(TaskType::getName(11), "waiting for sending", User::getCurrentUserId(), User::getCurrentUserId(), new DateTime(), 11, $saveSignal->signalID, $messageId, $post);
        $task->action = $action;
        $task->status = 2;
        $taskController = new TaskController($task, new TaskView());
        if ($taskController->save())
            return "succeed";
        else
            return "failed";
    }

    public static function sendSMSNow($taskId, $phoneNumber, $text) {
        $sms = new SMS($phoneNumber, $text);
        if ($sms->send() == "OK") {
            $task = Task::withId($taskId);
            $taskController = new TaskController($task, new TaskView());
            if ($taskController->markComplete())
                return "succeed";
            else
                return "failed";
        }
        return "failed";
    }

    public static function isMarkForSendingLater($streamId, $messageId) {
        $query = "SELECT * FROM tasks LEFT JOIN signals ON tasks.signalid=signals.signalid WHERE tasktype='10' AND streamid='$streamId' AND messageid='$messageId'";
        $result = Database::getInstance()->query($query);
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow == 1) {
                return true;
            }
        }
        return false;
    }

    public static function getMailHTML($taskIds) {
        $taskIds = explode(';', rtrim($taskIds, ';'));
        $template = Task::getTemplate(1);
        $mainData = $template['maindata']; //template of thread on database
        $subData = $template['subdata']; //template of replies on database
        $db = Database::getInstance();

        //get subdata HTML from template
        $postHTML = '';
        for ($i = 0; $i < count($taskIds); $i++) {
            if ($taskIds[$i] != '') {
                $result = $db->query("SELECT * FROM tasks WHERE taskid='$taskIds[$i]'");
                $row = $result->dataTable->rows[0];
                $signal = Signal::withId($row['signalid']);
                $message = $signal->message;
                $text = str_replace('(javascript:void(0)) ', '', Signal::removeLinkForEmail($message->getLead()));
                if (strlen($text) > 250) {
                    $endPos = strpos($text, ' ', 200);
                    $text = substr($text, 0, $endPos);
                }
                $time = new DateTime($message->getTime());
                $postDate = $time->format("Y-m-d");
                $postTime = $time->format("H:i:s");
                $old = array("{postTitle}", "{postLink}", "{messageContent}", "{postDate}", "{postTime}");
                $new = array($message->getThreadTitle(), $message->getURL(), $text, $postDate, $postTime);
                $postHTML = $postHTML . str_replace($old, $new, $subData);
            }
        }
        //get maindata HTML from template
        if (count($taskIds) > 1) {
            $postTitle = "Please take a look at these discussions on social media";
            $sourceName = "posts";
        } else {
            $postTitle = $message->getThreadTitle();
            $sourceName = "post on " . str_replace('www.', '', $message->getSource());
        }
        $old = array('{postTitle}', '{sourceName}', '{subData}');
        $new = array($postTitle, $sourceName, $postHTML);
        $mailHTML = $mailHTML . str_replace($old, $new, $mainData);
        return htmlspecialchars($mailHTML);
    }

    public static function sendSMS($phoneNumber, $message) {
        $sms = new SMS($phoneNumber, $message);
        return $sms->send();
    }

    public static function getTagMetric($_filter) {
        $tagsMetric = Tag::getMetric($_filter);
        $result = array();
        foreach ($tagsMetric as $key => $metrics) {
            $result[$key] = Utils::sortTags($metrics);
        }
        return json_encode($result);
    }

    public static function getTopSources($filter) {
        return Metrics::getTopSources($filter);
    }

    public static function saveComparison($id, $name, $streamId1, $streamId2) {
        if ($id) {
            $comparison = Comparison::withId($id);
            if ($name != '0') {
                $comparison->name = $name;
                $comparison->streamId2 = $streamId2;
                $comparison->streamId3 = $streamId3;
                if ($comparison->save())
                    return "succeed";
                else
                    return "failed";
            }
            else {
                $comparison = Comparison::withId($id);
                return $comparison->delete();
            }
        } else {
            $comparison = Comparison::withData($name, $streamId1, $streamId2, $streamId3);
            if ($comparison->save())
                return "succeed";
            else
                return "failed";
        }
    }

    public static function getGroups() {
        $groups = Tag::getGroups();
        $result = array();
        foreach ($groups as $group) {
            $groupData['groupid'] = $group['id'];
            $groupData['groupname'] = $group['name'];
            $groupData['userid'] = $group['userid'];
            $result[] = $groupData;
        }
        return json_encode($result);
    }

    public static function listTag($groupId) {
        return json_encode(Tag::getTagsByGroup($groupId));
    }

    public static function addTagGroup($groupName) {
        return Tag::addGroup($groupName);
    }

    public static function modifyGroup($groupId, $groupName) {
        $group = Group::withId($groupId);
        $group->name = $groupName;
        if ($group->save())
            return 'succeed';
        else
            return 'failed';
    }

    public static function deleteGroup($groupId) {
        $group = Group::withId($groupId);
        if ($group->delete())
            return 'succeed';
        else
            return 'failed';
    }

    public static function getSentimentByPlatforms($filter) {
        return json_encode(Utils::sortPlatforms(Metrics::getsentimentByPlatforms($filter)));
    }

    public static function getSentimentBySources($filter) {
        return json_encode(Utils::sortPlatforms(Metrics::getSentimentBySources($filter)));
    }
    
    public static function getHostInfo() {
        $response = array(
            'hostname' => $_SERVER['SERVER_NAME'],
            'ip' => $_SERVER['SERVER_ADDR'],
            'port' => $_SERVER['SERVER_PORT'],
            'datetime' => date("l dS of F Y H:i:s T"),
            'PHP_version' => PHP_VERSION
        );
        return $response;
    }

}
